Skip to content

feat(pegs): L3 oracle-events consumer — stables/oracle_events.py (#302)#307

Draft
spalen0 wants to merge 14 commits into
mainfrom
feat/peg-monitoring-l3-events
Draft

feat(pegs): L3 oracle-events consumer — stables/oracle_events.py (#302)#307
spalen0 wants to merge 14 commits into
mainfrom
feat/peg-monitoring-l3-events

Conversation

@spalen0

@spalen0 spalen0 commented Jun 29, 2026

Copy link
Copy Markdown
Collaborator

Closes #302. Layer 3 (consumer side) of peg monitoring.

⚠️ Stacked on #306 (L2). Base is feat/peg-monitoring-l2-oracles; the diff below is L3-only. The chain is #305#306 → this. Each retargets to main as its parent merges.

What this is

An Envio GraphQL consumer that reads Chainlink AnswerUpdated(current, roundId, updatedAt) rows indexed by chain-events/yearn-indexing-test (issue #31) and turns per-feed anomalies into alerts. Where L2 polls the current round hourly, L3 consumes the full event stream so no round is missed between polls. Mirrors protocols/timelock/timelock_alerts.py.

Detection (pure, unit-tested)

Anomaly Rule Severity
Large round-over-round jump |Δanswer| / prev ≥ JUMP_THRESHOLD (default 10%, env-tunable) HIGH
Missed-heartbeat gap updatedAt gap between consecutive rounds > heartbeat + buffer HIGH
Sequence anomaly roundId does not strictly increase CRITICAL

Jumps are percentage-based (unit-independent), so no per-feed decimals are needed and BTC-denominated feeds aren't false-flagged the way an absolute threshold would.

Routing & dedupe

  • Alerts use PeggedAsset.protocol + channel (the L2 fix), so emergency dispatch fires for ethena/cap/infinifi.
  • De-dupe via a per-aggregator blockTimestamp cursor. A small context window is fetched before each cursor so the first new round has a prior round to diff against; alerts only fire for rounds strictly newer than the cursor → reruns never re-alert the same round (acceptance criterion). Cursor advances only when every send lands (same trade-off as timelock_alerts).

Address sourcing (the subtle part, per indexer #31)

AnswerUpdated is emitted by the underlying aggregator (which rotates on phase upgrades), and its indexed params are current/roundIdnot the address — so Envio can't scope it by feed. The consumer resolves each feed proxy's current aggregator() on-chain (batched) and maps aggregator → asset, so it always tracks the live aggregator. A phase rotation naturally surfaces as a staleness gap in L2.

GraphQL field names are centralised in _F_* constants to align with #31's final schema with a one-line change if the indexer names a field differently.

Automation

Added stables-oracle-events to the hourly profile (renders; 25 tasks). Hourly is sufficient given the cursor + context window guarantees no missed rounds; can move to the 10-min profile if you want lower latency.

Validation

  • ruff + mypy clean on the new module.
  • 651 passed, 6 skipped (full suite; +14 new L3 tests: jump/gap/sequence detection, dedup gate with prior-round context, cursor advance, row parsing, dispatch routing).
  • Live smoke: resolved all 6 underlying aggregators on-chain (e.g. cbBTC proxy 0x2665…0x5e24…), queried the real Envio endpoint, and — since chore: use cache for safe queued txs #31's entity isn't indexed yet — degraded gracefully via send_error_message.

Dependency / follow-up

🤖 Generated with Claude Code

spalen0 and others added 14 commits June 29, 2026 18:28
Establish the building blocks consumed by all peg/oracle monitoring layers
(L1 market depeg, L2 oracle health, L3 event consumers):

- Promote ChainlinkAggregator.json to common-abi/ and repoint protocols/ustb.
- Add utils/chainlink.py: batched latestRoundData reader (read_feeds) plus
  pure, unit-tested helpers — scale_price, is_stale(updated_at, heartbeat,
  buffer), and round/answeredInRound sanity checks. Generalizes the logic
  previously inline in protocols/ustb/main.py.
- Add utils/pegged_assets.py: PeggedAsset dataclass + PegTarget enum (USD=1,
  BTC=live BTC/USD via DeFiLlama) as the single registry consumed by L1/L2/L3,
  with optional chainlink_feed (+heartbeat) and rate_oracle (monotonic) refs.
  depeg_pct expresses peg deviation, not an absolute floor.
- Registry covers USDC, USDT, USDS, USDe, cUSD, iUSD, siUSD, cbBTC, LBTC.
  Token addresses and Chainlink feeds verified on mainnet; siUSD is a marked
  placeholder pending address verification.
- Unit tests for staleness, round sanity, deviation, and registry helpers.

ruff + mypy clean (new files); 42 tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Layer 2 of peg monitoring: an hourly script that watches the on-chain oracles
our lending markets actually liquidate on, driven by the shared PeggedAsset
registry. Stacks on the foundation branch (#299 / #305).

Per Chainlink-backed asset (USDC, USDT, USDS, USDe, cbBTC, LBTC):
- staleness (now - updatedAt > heartbeat + buffer),
- round sanity / monotonicity (positive answer, completed round,
  answeredInRound >= roundId, non-decreasing roundId vs cached run),
- deviation from peg (oracle price vs PegTarget),
- oracle <-> market divergence (Chainlink vs DeFiLlama) — the liquidation signal.

Per-check logic is pure (Alert | None) so forced-stale / forced-divergence /
off-peg / round-malfunction cases are unit-tested without a chain.

Rate / fundamental oracles: generic monotonicity + delta-vs-cached handler
(apyusd approach); a monotonic/capped decrease is CRITICAL (per #196). LBTC
Redstone is already covered by a Tenderly alert, so it is documented in
TENDERLY_COVERED and not double-polled; gap-analysis notes included.

Foundation: add ChainlinkFeed.quote (PegTarget) so BTC-denominated feeds
(LBTC/BTC) convert to a USD basis for divergence; LBTC feed marked quote=BTC.

Wired into the hourly profile in automation/jobs.yaml (renders; 24 tasks).

Validation: ruff + mypy clean (new files); 52 peg tests + 13 automation tests
pass; live mainnet smoke run reads all 6 feeds and computes peg/market
deviations correctly (LBTC $60,405 = 1.0043 BTC x $60,146).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…301)

Address review on stables/oracles.py:

1. Emergency dispatch (utils/dispatch.dispatch_emergency_withdrawal) keys off
   Alert.protocol and skips anything outside DISPATCHABLE_PROTOCOLS. Alerts were
   hardcoding protocol="pegs" and putting the owner only in channel, so an USDe
   oracle failure routed to Telegram but never triggered ethena's emergency
   withdrawal. Rename PeggedAsset.channel -> protocol (the logical owner) and add
   an optional channel override (empty falls back to protocol routing). Alerts
   now emit protocol=asset.protocol, channel=asset.channel, so dispatch fires for
   ethena/cap/infinifi while Telegram routing is unchanged.

2. The round cache was overwritten with the current roundId unconditionally, so a
   backwards roundId became the new baseline and the regression was caught only
   once. Add pure next_cached_round(): a health-gated high-water mark that never
   lowers the cached round or stores a malfunctioning one.

Tests: add dispatch-routing coverage (alert.protocol in DISPATCHABLE_PROTOCOLS)
and next_cached_round cases. Full suite: 637 passed, 6 skipped. ruff + mypy clean
(new files). Live no-send smoke reads all six feeds, 0 alerts under current
conditions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Layer 3 of peg monitoring: an Envio GraphQL consumer that reads Chainlink
AnswerUpdated rows and turns per-feed anomalies into alerts. Stacks on L2 (#301)
for the shared registry routing. Mirrors protocols/timelock/timelock_alerts.py.

Detects per feed (pure, unit-tested functions):
- large round-over-round jumps (|Δanswer|/prev >= JUMP_THRESHOLD, default 10%),
- missed-heartbeat gaps (updatedAt gap > feed heartbeat + buffer),
- sequence anomalies (roundId not strictly increasing -> CRITICAL).

Routing uses PeggedAsset.protocol + channel so alerts reach the owning protocol
and its emergency dispatch (consistent with the L2 fix). De-dupe via a
per-aggregator blockTimestamp cursor, advanced only when every send lands (same
trade-off as timelock_alerts: re-alert on retry is acceptable, dropping is not).

Address sourcing (per indexer issue chain-events/yearn-indexing-test#31):
AnswerUpdated is emitted by the underlying aggregator (rotates on phase upgrades),
which Envio can't scope by feed. The consumer resolves each feed proxy's current
aggregator() on-chain (batched) and maps aggregator -> asset, so it always tracks
the live aggregator. GraphQL field names are centralised in _F_* constants to
align with #31's final schema.

Wired into the hourly profile (renders; 25 tasks). ruff + mypy clean (new files);
651 passed, 6 skipped. Live smoke resolved all 6 aggregators on-chain and handled
the not-yet-indexed entity gracefully via send_error_message.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
#302)

detect_anomalies sorted rounds by (block_timestamp, round_id). round_id is the
field whose monotonicity we validate, so using it as the sort tiebreaker reorders
same-block events into apparent monotonicity and hides a backwards round: 102
followed by 101 at the same block_timestamp sorted to 101->102 and produced 0
alerts.

Carry blockNumber + logIndex through parse_round (and select logIndex in the
GraphQL query), and sort by OracleRound.event_order = (block_number, log_index),
the canonical on-chain emission order. block_timestamp remains the dedup cursor.

Add a regression test: a backwards round sharing a block_timestamp, distinguished
only by logIndex, now produces a CRITICAL sequence-anomaly alert.

Full suite: 652 passed, 6 skipped. ruff + mypy clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Remove is_stale and round_issues/is_round_healthy from utils/chainlink.py:
  no longer reliable oracle health indicators and unused by production code.
- Replace the unverified siUSD placeholder entry with the existing verified
  iUSD (infinifi) entry; siUSD is yield-bearing staked iUSD and shouldn't be
  modeled as a flat-peg deviation. Drop the now-unused PLACEHOLDER_ADDRESS.
- Update tests to match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…nitor

- Add WBTC to the peg registry (BTC peg, verified WBTC/BTC Chainlink feed).
- ChainlinkFeed gains an explicit `quote: PegTarget` so consumers can interpret
  mixed feed denominations (WBTC/LBTC are BTC-quoted ~1.0; cbBTC is USD-quoted).
- PeggedAsset gains `downside_only`; is_depegged becomes asymmetric for BTC
  wrappers (WBTC/cbBTC/LBTC) so a legit move above peg (e.g. LBTC at ~1.004 BTC)
  no longer false-alerts — only a drop below peg triggers.
- lrt-pegs curve monitor: read pools via balances(i) (works for modern and
  legacy pools) and add the deep Lido stETH/ETH pool as the canonical
  wstETH-vs-ETH depeg gauge (wstETH deterministically wraps stETH).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resolve conflicts in utils/pegged_assets.py and reconcile the foundation's
round-helper removal with the L2 oracle monitor.

Registry (utils/pegged_assets.py):
- Keep L2's protocol/channel split (oracles.py + tests + emergency dispatch key
  off Alert.protocol); adopt the foundation's downside_only field, WBTC entry,
  fuller ChainlinkFeed docstring, and LBTC downside_only.
- Drop the unverified siUSD placeholder (foundation tracks iUSD instead).

Round-sanity helpers (foundation dropped is_stale/round_issues/is_round_healthy
from utils/chainlink.py as "no longer reliable / unused", but L2's oracles.py
uses them):
- Per maintainer guidance, keep the staleness + round checks but make them safe
  for feeds that return constant or zero roundId/updatedAt: inline round_issues/
  is_round_healthy privately into oracles.py (chainlink.py stays slim) and gate
  check_staleness + check_round_health on a new ChainlinkFeed.reports_round_metadata
  flag (default True; set False for non-conforming feeds).
- Update cbBTC off-peg test for the now-downside_only semantics; add gate tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The sequence-anomaly (roundId) and missed-heartbeat-gap (updatedAt) checks in
oracle_events.py rely on a feed reporting reliable round metadata. Honor the
same ChainlinkFeed.reports_round_metadata flag L2 uses so feeds that return
constant or zero roundId/updatedAt don't false-positive; the answer-based jump
check always runs. Also warn when an AnswerUpdated query hits its row limit
(newest rounds deferred to the next run). Adds gating tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Base automatically changed from feat/peg-monitoring-l2-oracles to feat/peg-monitoring-foundation June 30, 2026 17:01
Base automatically changed from feat/peg-monitoring-foundation to main June 30, 2026 17:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant